package com.phpxiu.app.api.callback;

import com.phpxiu.app.config.Constants;
import com.phpxiu.app.controller.avcontroller.QavsdkControl;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.push.MessageEvent;
import com.phpxiu.app.push.PushUtil;
import com.tencent.TIMCallBack;
import com.tencent.TIMManager;
import com.tencent.TIMOfflinePushSettings;
import com.tencent.TIMUser;
import com.tencent.av.sdk.AVError;
import com.tencent.bugly.imsdk.crashreport.CrashReport;

/**
 * Created by 吴金洲 on 2016/8/10
 */
public class EnterRoomChecker implements TIMCallBack {
    private volatile static EnterRoomChecker instance;

    private EnterRoomChecker(){

    }
    public static EnterRoomChecker getInstance(){
        if (instance == null) {
            synchronized (EnterRoomChecker.class) {
                if (instance == null) {
                    instance = new EnterRoomChecker();
                }
            }
        }
        return instance;
    }

    /**
     * 登录IM
     * @param identify 用户id
     * @param userSig//登录获取的签名
     */
    public void IMLogin(String identify,String userSig){
        TIMUser user = new TIMUser();
        user.setAccountType(String.valueOf(Constants.ACCOUNT_TYPE));
        user.setAppIdAt3rd(String.valueOf(Constants.SDK_APPID));
        user.setIdentifier(identify);
        //发起登录请求
        TIMManager.getInstance().login(Constants.SDK_APPID, user, userSig,this);
    }

    /**
     * IM 登录失败
     * @param i
     * @param s
     */
    @Override
    public void onError(int i, String s) {
        //发送日志到错误统计
        CrashReport.postCatchedException(new Throwable("Main IM Login failed：" + i + "-->" + s));
    }

    /**
     * IM登录成功
     */
    @Override
    public void onSuccess() {
        TIMOfflinePushSettings SETTINGS = new TIMOfflinePushSettings();
        SETTINGS.setEnabled(true);
        TIMManager.getInstance().configOfflinePushSettings(SETTINGS);
        //初始化程序后台后消息推送
        PushUtil.getInstance();
        //初始化消息监听
        MessageEvent.getInstance();
        if(startAVSDK()){
        }else{
            CrashReport.postCatchedException(new Exception("登录失败,AV SDK初始化失败"));
        }
    }

    /**
     * 初始化音视频SDK
     */
    public static boolean startAVSDK() {
        QavsdkControl.getInstance().setAvConfig(Constants.SDK_APPID, "" + Constants.ACCOUNT_TYPE, MySelfInfo.getInstance().getId(), MySelfInfo.getInstance().getUserSig());
        int startResult=QavsdkControl.getInstance().startContext();
        if(startResult!=AVError.AV_OK){
            return false;
        }
        return true;
    }
}
